package br.unipampa.view;

import br.unipampa.model.Estudante;
import br.unipampa.utilitarios.ImplementaIcone;
import br.unipampa.utilitarios.LimparCampos;
import br.unipampa.utilitarios.TestarConexao;
import br.unipampa.utilitarios.ThreadTimer;
import br.unipampa.utilitarios.TratarUsuario;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;

/**
 * @author Gabriel Moro
 * @since 15/03/2013
 * @version 1.2
 */
public class FrameLogin extends javax.swing.JFrame implements LimparCampos, ImplementaIcone {

    private FormularioPrincipal frame;
    private CadastroDeUsuarios cadastroUsuarios;
    private Estudante estudante;
    private TratarUsuario trataEntrada;
    private ThreadTimer thread;
    private TestarConexao test;
    private Image iconeTitulo;

    /**
     * Creates new form FrameLogin
     */
    public FrameLogin() {
        initComponents();
        setResizable(false);
        setLocationRelativeTo(null);
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormularioPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormularioPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormularioPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormularioPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                ApoioDeInterface.mensagemSair();
            }
        });
        tratarIcone();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelInterno = new javax.swing.JPanel();
        lblImagem = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtLogin = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jpfSenha = new javax.swing.JPasswordField();
        btnAcessar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Bem vindo a Agenda Universitária Virtual");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jPanelInterno.setBackground(new java.awt.Color(204, 204, 255));
        jPanelInterno.setForeground(new java.awt.Color(102, 102, 102));

        lblImagem.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lblImagem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unipampa/icons/agenda.png"))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel1.setText("Login:");

        txtLogin.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N

        jLabel2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        jLabel2.setText("Senha:");

        jpfSenha.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N

        btnAcessar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unipampa/icons/imgOk.png"))); // NOI18N
        btnAcessar.setToolTipText("Acessar Sistema");
        btnAcessar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAcessarActionPerformed(evt);
            }
        });
        btnAcessar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnAcessarKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                btnAcessarKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanelInternoLayout = new javax.swing.GroupLayout(jPanelInterno);
        jPanelInterno.setLayout(jPanelInternoLayout);
        jPanelInternoLayout.setHorizontalGroup(
            jPanelInternoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelInternoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblImagem)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelInternoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanelInternoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanelInternoLayout.createSequentialGroup()
                        .addComponent(jpfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnAcessar, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(txtLogin))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        jPanelInternoLayout.setVerticalGroup(
            jPanelInternoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelInternoLayout.createSequentialGroup()
                .addGroup(jPanelInternoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelInternoLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblImagem))
                    .addGroup(jPanelInternoLayout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addGroup(jPanelInternoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanelInternoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelInternoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jpfSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnAcessar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelInterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelInterno, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAcessarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAcessarActionPerformed
        acessarSystem();
    }//GEN-LAST:event_btnAcessarActionPerformed

    private void btnAcessarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnAcessarKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_btnAcessarKeyReleased

    private void btnAcessarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnAcessarKeyPressed
      if(evt.getKeyCode()==evt.VK_ENTER)
          acessarSystem();
 
    }//GEN-LAST:event_btnAcessarKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAcessar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanelInterno;
    private javax.swing.JPasswordField jpfSenha;
    private javax.swing.JLabel lblImagem;
    private javax.swing.JTextField txtLogin;
    // End of variables declaration//GEN-END:variables

    @Override
    public void limparCampos() {
        txtLogin.setText("");
        jpfSenha.setText("");
    }

    @Override
    public void tratarIcone() {
        //definindo icone do sistema
        this.iconeTitulo = Toolkit.getDefaultToolkit().getImage(
                getClass().getResource("/br/unipampa/icons/iconeOfSystem.png"));

        this.setIconImage(this.iconeTitulo);
    }
    
    private void acessarSystem(){
        this.test = new TestarConexao();
        if (this.test.testarConexaoComBanco()) {

            this.trataEntrada = new TratarUsuario();
            String login = txtLogin.getText();
            char[] arraySenha = jpfSenha.getPassword();
            String senha = String.valueOf(arraySenha);

            this.frame = new FormularioPrincipal();
            this.thread = new ThreadTimer(this.frame);
            if (this.trataEntrada.verificarCredenciais(login, senha, this.frame)) {
                FrameLogin.this.dispose();
                this.thread.start();
            } else {
                ApoioDeInterface.mensagemAdvertindoLogin();
                limparCampos();
            }
        } else {
            ApoioDeInterface.mensagemNaoExistConexao();
            System.exit(0);
        }
}}